package ZJX_net

import (
	ZJX_interface "TCP-sever/interface"
	"errors"
	"fmt"
	"sync"
)

type ConnManager struct {
	connMap  map[uint32]ZJX_interface.IConnection
	connLock sync.RWMutex
}

func NewConnManager() ZJX_interface.IConnManager {
	return &ConnManager{
		connMap:  make(map[uint32]ZJX_interface.IConnection),
		connLock: sync.RWMutex{},
	}
}

//添加连接
func (c *ConnManager) Add(connection ZJX_interface.IConnection) {
	c.connLock.Lock()
	defer c.connLock.Unlock()

	c.connMap[connection.GetConnID()] = connection
	fmt.Println("Add conn success.   connId :", connection.GetConnID())
}

//删除连接
func (c *ConnManager) Delete(conn ZJX_interface.IConnection) {
	c.connLock.Lock()
	c.connLock.Unlock()

	delete(c.connMap, conn.GetConnID())
	fmt.Println("Delete conn success.   connId :", conn.GetConnID())
}

//查找连接
func (c *ConnManager) Get(connId uint32) (ZJX_interface.IConnection, error) {
	c.connLock.RLock()
	c.connLock.RUnlock()

	if conn, ok := c.connMap[connId]; ok {
		return conn, nil
	} else {
		return nil, errors.New(fmt.Sprintf("Can not find conn , connId:%d", connId))
	}
}

//得到连接总数
func (c *ConnManager) Size() int {
	return len(c.connMap)
}

//清除全部连接
func (c *ConnManager) Clear() {
	c.connLock.Lock()
	defer c.connLock.Unlock()

	for _, conn := range c.connMap {
		//停止连接
		conn.Stop()
	}

	fmt.Println("All conn close..............................")
}
